package com.hunttown.mes.manage.controller.common;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.common.amap.AmapUtils;
import com.hunttown.mes.common.utils.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 提供公共方法
 * created by wangjunfu on 2019-06-01
 */
@Controller
@RequestMapping(value = "/public")
public class PublicController {

    //region 汉字转拼音

    /**
     * 汉字转拼音
     *
     * @param chinese 要转拼音的汉字
     * @param type    1只转首字母（小写） 2只转首字母（大写） 3全部拼音（小写） 4全部拼音（大写） 5全部拼音（并且首字母大写）
     * @return pingyin
     */
    @RequestMapping(value = "/getChinesePinying", method = RequestMethod.POST)
    @ResponseBody
    public String getChinesePinying(String chinese, Integer type) {
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            if (StringUtils.isNotBlank(chinese)) {
                String pingyin = "";

                if (type == 1) {
                    pingyin = ChineseToPinyinUtils.ToFirstChar(chinese);
                }

                if (type == 2) {
                    pingyin = ChineseToPinyinUtils.ToFirstChar(chinese).toUpperCase();
                }

                if (type == 3) {
                    pingyin = ChineseToPinyinUtils.ToPinyin(chinese);
                }

                if (type == 4) {
                    pingyin = ChineseToPinyinUtils.ToPinyin(chinese).toUpperCase();
                }

                if (type == 5) {
                    pingyin = ChineseToPinyinUtils.ToPinyinFirstCharUpper(chinese);
                }

                map.put("pingyin", pingyin);
                map = OperateCode.CompositionResult(map, 1);

            } else {
                map = OperateCode.CompositionResult(map, -10, "转拼音的汉字为空！");
            }

            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 生成随机数

    /**
     * 生成随机数
     *
     * @param genType 生成类型：1纯字母 2纯数字 3混合
     * @param len     长度
     * @return 随机数
     */
    @RequestMapping(value = "/getKeyGen", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getKeyGen(Integer genType, Integer len) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (genType == null) {
            genType = 3;
        }

        if (len == null) {
            len = 4;
        }

        try {
            String code = "";

            switch (genType) {
                case 1:
                    code = GetRandomUtils.GetRandomLetter(len);
                    break;
                case 2:
                    code = GetRandomUtils.GetRandomNumber(len);
                    break;
                default:
                    code = GetRandomUtils.GetRandom(len);
            }

            map.put("code", code);
            map.put("returnCode", 1);

        } catch (Exception ex) {
            //todo
        }

        return map;
    }
    //endregion

    //region 生成会员卡号

    /**
     * 生成会员卡号
     *
     * @param genType 生成类型：1纯字母 2纯数字 3混合
     * @param len     长度
     * @return map
     */
    @RequestMapping(value = "/getUserCardNo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getUserCardNo(Integer genType, Integer len) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (genType == null) {
            genType = 3;
        }

        if (len == null) {
            len = 4;
        }

        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            String code = format.format(new Date());

            //四位随机数
            String code2 = GetRandomUtils.GetRandomNumber(4);

            map.put("code", code + code2);
            map.put("returnCode", 1);

        } catch (Exception ex) {
            //todo
        }

        return map;
    }
    //endregion

    //region 获取地址经纬度

    /**
     * 获取地址经纬度
     *
     * @param city    城市
     * @param address 关键字
     * @return 经纬坐标
     */
    @RequestMapping(value = "/getAmapGeo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getAmapGeo(String city, String address) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (StringUtils.isBlank(city) || StringUtils.isBlank(address)) {
            map.put("returnMessage", "查询地点为空");
            return map;
        }

        String location = AmapUtils.getGeo(city.trim(), address.trim());

        if (location.equals("")) {
            map.put("returnMessage", "未获取到定位信息");
            return map;
        }

        map.put("location", location);
        map.put("returnCode", 1);
        return map;
    }
    //endregion

    //region 获取字符串的Base64编码

    /**
     * 获取字符串的Base64编码
     *
     * @param character 字符串
     * @return map
     */
    @RequestMapping(value = "/getBase64", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getBase64(String character) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);
        map.put("code", "");

        if (StringUtils.isBlank(character)) {
            return map;
        }

        byte[] numberBytes = character.trim().getBytes(StandardCharsets.UTF_8);
        String code = Base64Utils.encodeToString(numberBytes);

        map.put("returnCode", 1);
        map.put("code", code);

        return map;
    }
    //endregion

    //region 生成code128条形吗

    /**
     * 生成code128条形吗
     *
     * @param response res
     * @param barCode  要生成的数字
     */
    @RequestMapping(value = "/getSnBar", method = RequestMethod.GET)
    public void getSnBar(HttpServletResponse response, String barCode) {

        //条形码
        byte[] bytes = BarCodeUtils.generateBarCode128(barCode, 10.00, 0.3, true, false);

        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);
        response.setContentType("image/png");

        // 将图像输出到Servlet输出流中。
        ServletOutputStream output;

        try {
            output = response.getOutputStream();
            InputStream in = new ByteArrayInputStream(bytes);

            int len;
            byte[] buf = new byte[1024];

            while ((len = in.read(buf)) != -1) {
                output.write(buf, 0, len);
            }

            output.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //endregion
}
